﻿    /*
 * DotNetCrypt - an open source library of cryptographic algorithms for .NET
 * Copyright (C) 2009 David Musgrove
 * 
 * This file is part of DotNetCrypt.
 *
 * DotNetCrypt is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DotNetCrypt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Security.Cryptography;

namespace DotNetCrypt
{
    /// <summary>
    /// Performs a cryptographic transformation of data using the
    /// <see cref="DES" /> algorithm. This class cannot be inherited.
    /// </summary>
    // ReSharper disable InconsistentNaming
    public sealed class DESManagedTransform : ManagedTransformBase
// ReSharper restore InconsistentNaming
    {
        private readonly byte[] _key;
        private uint[] _expandedKey;

        #region S-box arrays

        private static readonly uint[] _sBox1 = {
                                                0x01010400, 0x00000000, 0x00010000, 0x01010404,
                                                0x01010004, 0x00010404, 0x00000004, 0x00010000,
                                                0x00000400, 0x01010400, 0x01010404, 0x00000400,
                                                0x01000404, 0x01010004, 0x01000000, 0x00000004,
                                                0x00000404, 0x01000400, 0x01000400, 0x00010400,
                                                0x00010400, 0x01010000, 0x01010000, 0x01000404,
                                                0x00010004, 0x01000004, 0x01000004, 0x00010004,
                                                0x00000000, 0x00000404, 0x00010404, 0x01000000,
                                                0x00010000, 0x01010404, 0x00000004, 0x01010000,
                                                0x01010400, 0x01000000, 0x01000000, 0x00000400,
                                                0x01010004, 0x00010000, 0x00010400, 0x01000004,
                                                0x00000400, 0x00000004, 0x01000404, 0x00010404,
                                                0x01010404, 0x00010004, 0x01010000, 0x01000404,
                                                0x01000004, 0x00000404, 0x00010404, 0x01010400,
                                                0x00000404, 0x01000400, 0x01000400, 0x00000000,
                                                0x00010004, 0x00010400, 0x00000000, 0x01010004
                                };

        private static readonly uint[] _sBox2 = {
                                                0x80108020, 0x80008000, 0x00008000, 0x00108020,
                                                0x00100000, 0x00000020, 0x80100020, 0x80008020,
                                                0x80000020, 0x80108020, 0x80108000, 0x80000000,
                                                0x80008000, 0x00100000, 0x00000020, 0x80100020,
                                                0x00108000, 0x00100020, 0x80008020, 0x00000000,
                                                0x80000000, 0x00008000, 0x00108020, 0x80100000,
                                                0x00100020, 0x80000020, 0x00000000, 0x00108000,
                                                0x00008020, 0x80108000, 0x80100000, 0x00008020,
                                                0x00000000, 0x00108020, 0x80100020, 0x00100000,
                                                0x80008020, 0x80100000, 0x80108000, 0x00008000,
                                                0x80100000, 0x80008000, 0x00000020, 0x80108020,
                                                0x00108020, 0x00000020, 0x00008000, 0x80000000,
                                                0x00008020, 0x80108000, 0x00100000, 0x80000020,
                                                0x00100020, 0x80008020, 0x80000020, 0x00100020,
                                                0x00108000, 0x00000000, 0x80008000, 0x00008020,
                                                0x80000000, 0x80100020, 0x80108020, 0x00108000
                                };

        private static readonly uint[] _sBox3 = {
                                                0x00000208, 0x08020200, 0x00000000, 0x08020008,
                                                0x08000200, 0x00000000, 0x00020208, 0x08000200,
                                                0x00020008, 0x08000008, 0x08000008, 0x00020000,
                                                0x08020208, 0x00020008, 0x08020000, 0x00000208,
                                                0x08000000, 0x00000008, 0x08020200, 0x00000200,
                                                0x00020200, 0x08020000, 0x08020008, 0x00020208,
                                                0x08000208, 0x00020200, 0x00020000, 0x08000208,
                                                0x00000008, 0x08020208, 0x00000200, 0x08000000,
                                                0x08020200, 0x08000000, 0x00020008, 0x00000208,
                                                0x00020000, 0x08020200, 0x08000200, 0x00000000,
                                                0x00000200, 0x00020008, 0x08020208, 0x08000200,
                                                0x08000008, 0x00000200, 0x00000000, 0x08020008,
                                                0x08000208, 0x00020000, 0x08000000, 0x08020208,
                                                0x00000008, 0x00020208, 0x00020200, 0x08000008,
                                                0x08020000, 0x08000208, 0x00000208, 0x08020000,
                                                0x00020208, 0x00000008, 0x08020008, 0x00020200
                                };

        private static readonly uint[] _sBox4 = {
                                                0x00802001, 0x00002081, 0x00002081, 0x00000080,
                                                0x00802080, 0x00800081, 0x00800001, 0x00002001,
                                                0x00000000, 0x00802000, 0x00802000, 0x00802081,
                                                0x00000081, 0x00000000, 0x00800080, 0x00800001,
                                                0x00000001, 0x00002000, 0x00800000, 0x00802001,
                                                0x00000080, 0x00800000, 0x00002001, 0x00002080,
                                                0x00800081, 0x00000001, 0x00002080, 0x00800080,
                                                0x00002000, 0x00802080, 0x00802081, 0x00000081,
                                                0x00800080, 0x00800001, 0x00802000, 0x00802081,
                                                0x00000081, 0x00000000, 0x00000000, 0x00802000,
                                                0x00002080, 0x00800080, 0x00800081, 0x00000001,
                                                0x00802001, 0x00002081, 0x00002081, 0x00000080,
                                                0x00802081, 0x00000081, 0x00000001, 0x00002000,
                                                0x00800001, 0x00002001, 0x00802080, 0x00800081,
                                                0x00002001, 0x00002080, 0x00800000, 0x00802001,
                                                0x00000080, 0x00800000, 0x00002000, 0x00802080
                                };

        private static readonly uint[] _sBox5 = {
                                                0x00000100, 0x02080100, 0x02080000, 0x42000100,
                                                0x00080000, 0x00000100, 0x40000000, 0x02080000,
                                                0x40080100, 0x00080000, 0x02000100, 0x40080100,
                                                0x42000100, 0x42080000, 0x00080100, 0x40000000,
                                                0x02000000, 0x40080000, 0x40080000, 0x00000000,
                                                0x40000100, 0x42080100, 0x42080100, 0x02000100,
                                                0x42080000, 0x40000100, 0x00000000, 0x42000000,
                                                0x02080100, 0x02000000, 0x42000000, 0x00080100,
                                                0x00080000, 0x42000100, 0x00000100, 0x02000000,
                                                0x40000000, 0x02080000, 0x42000100, 0x40080100,
                                                0x02000100, 0x40000000, 0x42080000, 0x02080100,
                                                0x40080100, 0x00000100, 0x02000000, 0x42080000,
                                                0x42080100, 0x00080100, 0x42000000, 0x42080100,
                                                0x02080000, 0x00000000, 0x40080000, 0x42000000,
                                                0x00080100, 0x02000100, 0x40000100, 0x00080000,
                                                0x00000000, 0x40080000, 0x02080100, 0x40000100
                                };

        private static readonly uint[] _sBox6 = {
                                                0x20000010, 0x20400000, 0x00004000, 0x20404010,
                                                0x20400000, 0x00000010, 0x20404010, 0x00400000,
                                                0x20004000, 0x00404010, 0x00400000, 0x20000010,
                                                0x00400010, 0x20004000, 0x20000000, 0x00004010,
                                                0x00000000, 0x00400010, 0x20004010, 0x00004000,
                                                0x00404000, 0x20004010, 0x00000010, 0x20400010,
                                                0x20400010, 0x00000000, 0x00404010, 0x20404000,
                                                0x00004010, 0x00404000, 0x20404000, 0x20000000,
                                                0x20004000, 0x00000010, 0x20400010, 0x00404000,
                                                0x20404010, 0x00400000, 0x00004010, 0x20000010,
                                                0x00400000, 0x20004000, 0x20000000, 0x00004010,
                                                0x20000010, 0x20404010, 0x00404000, 0x20400000,
                                                0x00404010, 0x20404000, 0x00000000, 0x20400010,
                                                0x00000010, 0x00004000, 0x20400000, 0x00404010,
                                                0x00004000, 0x00400010, 0x20004010, 0x00000000,
                                                0x20404000, 0x20000000, 0x00400010, 0x20004010
                                };

        private static readonly uint[] _sBox7 = {
                                                0x00200000, 0x04200002, 0x04000802, 0x00000000,
                                                0x00000800, 0x04000802, 0x00200802, 0x04200800,
                                                0x04200802, 0x00200000, 0x00000000, 0x04000002,
                                                0x00000002, 0x04000000, 0x04200002, 0x00000802,
                                                0x04000800, 0x00200802, 0x00200002, 0x04000800,
                                                0x04000002, 0x04200000, 0x04200800, 0x00200002,
                                                0x04200000, 0x00000800, 0x00000802, 0x04200802,
                                                0x00200800, 0x00000002, 0x04000000, 0x00200800,
                                                0x04000000, 0x00200800, 0x00200000, 0x04000802,
                                                0x04000802, 0x04200002, 0x04200002, 0x00000002,
                                                0x00200002, 0x04000000, 0x04000800, 0x00200000,
                                                0x04200800, 0x00000802, 0x00200802, 0x04200800,
                                                0x00000802, 0x04000002, 0x04200802, 0x04200000,
                                                0x00200800, 0x00000000, 0x00000002, 0x04200802,
                                                0x00000000, 0x00200802, 0x04200000, 0x00000800,
                                                0x04000002, 0x04000800, 0x00000800, 0x00200002
                                };

        private static readonly uint[] _sBox8 = {
                                                0x10001040, 0x00001000, 0x00040000, 0x10041040,
                                                0x10000000, 0x10001040, 0x00000040, 0x10000000,
                                                0x00040040, 0x10040000, 0x10041040, 0x00041000,
                                                0x10041000, 0x00041040, 0x00001000, 0x00000040,
                                                0x10040000, 0x10000040, 0x10001000, 0x00001040,
                                                0x00041000, 0x00040040, 0x10040040, 0x10041000,
                                                0x00001040, 0x00000000, 0x00000000, 0x10040040,
                                                0x10000040, 0x10001000, 0x00041040, 0x00040000,
                                                0x00041040, 0x00040000, 0x10041000, 0x00001000,
                                                0x00000040, 0x10040040, 0x00001000, 0x00041040,
                                                0x10001000, 0x00000040, 0x10000040, 0x10040000,
                                                0x10040040, 0x10000000, 0x00040000, 0x10001040,
                                                0x00000000, 0x10041040, 0x00040040, 0x10000040,
                                                0x10040000, 0x10001000, 0x10001040, 0x00000000,
                                                0x10041040, 0x00041000, 0x00041000, 0x00001040,
                                                0x00001040, 0x00040040, 0x10000000, 0x10041000
                                };

        private static readonly uint[] _leftHalfSwap = {
                                                0x00000000, 0x00000001, 0x00000100, 0x00000101,
                                                0x00010000, 0x00010001, 0x00010100, 0x00010101,
                                                0x01000000, 0x01000001, 0x01000100, 0x01000101,
                                                0x01010000, 0x01010001, 0x01010100, 0x01010101
                                };

        private static readonly uint[] _rightHalfSwap = {
                                                0x00000000, 0x01000000, 0x00010000, 0x01010000,
                                                0x00000100, 0x01000100, 0x00010100, 0x01010100,
                                                0x00000001, 0x01000001, 0x00010001, 0x01010001,
                                                0x00000101, 0x01000101, 0x00010101, 0x01010101
                                };

        #endregion

        internal DESManagedTransform(ISymmetricAlgorithm algorithm, byte[] rgbKey, byte[] rgbIv, TransformDirection transformDirection)
            : base(algorithm, rgbIv, transformDirection, Endianness.Big)
        {
            _key = rgbKey;
            ComputeKeySchedule();
        }

        private void ComputeKeySchedule()
        {
            _expandedKey = new uint[32];

            // Extract words from key.
            uint x = (uint)_key[0] << 24 |
                     (uint)_key[1] << 16 |
                     (uint)_key[2] << 8 |
                     _key[3];
            uint y = (uint)_key[4] << 24 |
                     (uint)_key[5] << 16 |
                     (uint)_key[6] << 8 |
                     _key[7];

            // Perform permuted choice 1.
            uint t = ((y >> 4) ^ x) & 0x0F0F0F0F;
            x ^= t;
            y ^= (t << 4);
            t = (y ^ x) & 0x10101010;
            x ^= t;
            y ^= t;

            x = (_leftHalfSwap[x & 0xF] << 3) |
                (_leftHalfSwap[(x >> 8) & 0xF] << 2) |
                (_leftHalfSwap[(x >> 16) & 0xF] << 1) |
                (_leftHalfSwap[(x >> 24) & 0xF]) |
                (_leftHalfSwap[(x >> 5) & 0xF] << 7) |
                (_leftHalfSwap[(x >> 13) & 0xF] << 6) |
                (_leftHalfSwap[(x >> 21) & 0xF] << 5) |
                (_leftHalfSwap[(x >> 29) & 0xF] << 4);

            y = (_rightHalfSwap[(y >> 1) & 0xF] << 3) |
                (_rightHalfSwap[(y >> 9) & 0xF] << 2) |
                (_rightHalfSwap[(y >> 17) & 0xF] << 1) |
                (_rightHalfSwap[(y >> 25) & 0xF]) |
                (_rightHalfSwap[(y >> 4) & 0xF] << 7) |
                (_rightHalfSwap[(y >> 12) & 0xF] << 6) |
                (_rightHalfSwap[(y >> 20) & 0xF] << 5) |
                (_rightHalfSwap[(y >> 28) & 0xF] << 4);

            x &= 0x0FFFFFFF;
            y &= 0x0FFFFFFF;

            int position = 0;
            for (int i = 0; i < 16; i++)
            {

                // Perform shifts.
                if (i < 2 || i == 8 || i == 15)
                {
                    x = (x << 1) | (x >> 27);
                    y = (y << 1) | (y >> 27);
                }
                else
                {
                    x = (x << 2) | (x >> 26);
                    y = (y << 2) | (y >> 26);
                }

                // Perform permuted shift 2 and store in module-level array.
                _expandedKey[position++] = ((x << 4) & 0x24000000) |
                                           ((x << 28) & 0x10000000) |
                                           ((x << 14) & 0x08000000) |
                                           ((x << 18) & 0x02080000) |
                                           ((x << 6) & 0x01000000) |
                                           ((x << 9) & 0x00200000) |
                                           ((x >> 1) & 0x00100000) |
                                           ((x << 10) & 0x00040000) |
                                           ((x << 2) & 0x00020000) |
                                           ((x >> 10) & 0x00010000) |
                                           ((y >> 13) & 0x00002000) |
                                           ((y >> 4) & 0x00001000) |
                                           ((y << 6) & 0x00000800) |
                                           ((y >> 1) & 0x00000400) |
                                           ((y >> 14) & 0x00000200) |
                                           (y & 0x00000100) |
                                           ((y >> 5) & 0x00000020) |
                                           ((y >> 10) & 0x00000010) |
                                           ((y >> 3) & 0x00000008) |
                                           ((y >> 18) & 0x00000004) |
                                           ((y >> 26) & 0x00000002) |
                                           ((y >> 24) & 0x00000001);

                _expandedKey[position++] = ((x << 15) & 0x20000000) |
                                           ((x << 17) & 0x10000000) |
                                           ((x << 10) & 0x08000000) |
                                           ((x << 22) & 0x04000000) |
                                           ((x >> 2) & 0x02000000) |
                                           ((x << 1) & 0x01000000) |
                                           ((x << 16) & 0x00200000) |
                                           ((x << 11) & 0x00100000) |
                                           ((x << 3) & 0x00080000) |
                                           ((x >> 6) & 0x00040000) |
                                           ((x << 15) & 0x00020000) |
                                           ((x >> 4) & 0x00010000) |
                                           ((y >> 2) & 0x00002000) |
                                           ((y << 8) & 0x00001000) |
                                           ((y >> 14) & 0x00000808) |
                                           ((y >> 9) & 0x00000400) |
                                           (y & 0x00000200) |
                                           ((y << 7) & 0x00000100) |
                                           ((y >> 7) & 0x00000020) |
                                           ((y >> 3) & 0x00000011) |
                                           ((y << 2) & 0x00000004) |
                                           ((y >> 21) & 0x00000002);

            }
        }

// ReSharper disable InconsistentNaming
        static private void IP(ref uint x, ref uint y)
// ReSharper restore InconsistentNaming
        {
            uint xWorking = x;
            uint yWorking = y;
            // Perform permutation.
            uint T = ((xWorking >> 4) ^ yWorking) & 0x0F0F0F0F;
            yWorking ^= T;
            xWorking ^= (T << 4);
            T = ((xWorking >> 16) ^ yWorking) & 0x0000FFFF;
            yWorking ^= T;
            xWorking ^= (T << 16);
            T = ((yWorking >> 2) ^ xWorking) & 0x33333333;
            xWorking ^= T;
            yWorking ^= (T << 2);
            T = ((yWorking >> 8) ^ xWorking) & 0x00FF00FF;
            xWorking ^= T;
            yWorking ^= (T << 8);
            yWorking = (yWorking << 1) | (yWorking >> 31);
            T = (xWorking ^ yWorking) & 0xAAAAAAAA;
            y = yWorking ^ T;
            xWorking ^= T;
            x = (xWorking << 1) | (xWorking >> 31);
        }

// ReSharper disable InconsistentNaming
        static private void IPInverse(ref uint x, ref uint y)
// ReSharper restore InconsistentNaming
        {
            uint xWorking = x;
            uint yWorking = y;
            // Perform inverse permutation.
            xWorking = (xWorking << 31) | (xWorking >> 1);
            uint T = (xWorking ^ yWorking) & 0xAAAAAAAA;
            xWorking ^= T;
            yWorking ^= T;
            yWorking = (yWorking << 31) | (yWorking >> 1);
            T = ((yWorking >> 8) ^ xWorking) & 0x00FF00FF;
            xWorking ^= T;
            yWorking ^= (T << 8);
            T = ((yWorking >> 2) ^ xWorking) & 0x33333333;
            xWorking ^= T;
            yWorking ^= (T << 2);
            T = ((xWorking >> 16) ^ yWorking) & 0x0000FFFF;
            yWorking ^= T;
            xWorking ^= (T << 16);
            T = ((xWorking >> 4) ^ yWorking) & 0x0F0F0F0F;
            y = yWorking ^ T;
            x = xWorking ^ (T << 4);
        }

        /// <summary>
        /// Performs the encryption transformation on a block of bytes that
        /// have been translated into words using the big endian convention.
        /// </summary>
        /// <param name="plain">
        /// The words to encrypt.
        /// </param>
        [CLSCompliant(false)]
        protected internal override void Encrypt(uint[] plain)
        {
            // Set initial values.
            uint high = plain[0];
            uint low = plain[1];
            int position = 0;

            // Perform initial permutation.
            IP(ref high, ref low);

            // Perform the sixteen rounds of DES encryption.
            for (int i = 0; i < 16; i++)
            {
                uint temp = low ^ _expandedKey[position++];
                high ^= _sBox8[temp & 0x3F] ^
                                _sBox6[(temp >> 8) & 0x3F] ^
                                _sBox4[(temp >> 16) & 0x3F] ^
                                _sBox2[(temp >> 24) & 0x3F];
                temp = ((low << 28) | (low >> 4)) ^ _expandedKey[position++];
                high ^= _sBox7[temp & 0x3F] ^
                                _sBox5[(temp >> 8) & 0x3F] ^
                                _sBox3[(temp >> 16) & 0x3F] ^
                                _sBox1[(temp >> 24) & 0x3F];
                temp = high;
                high = low;
                low = temp;
            }

            // Reverse the initial permutation.
            IPInverse(ref low, ref high);

            // Set the return values.
            plain[1] = high;
            plain[0] = low;
        }

        /// <summary>
        /// Performs the decryption transformation on a block of bytes that
        /// have been translated into words using the big endian convention.
        /// </summary>
        /// <param name="cipher">
        /// The words to decrypt.
        /// </param>
        [CLSCompliant(false)]
        protected internal override void Decrypt(uint[] cipher)
        {
            // Set initial values.
            uint high = cipher[0];
            uint low = cipher[1];
            int position = 30;

            // Perform initial permutation.
            IP(ref high, ref low);

            // Perform the sixteen rounds of DES encryption.
            for (int i = 0; i < 16; i++)
            {
                uint temp = low ^ _expandedKey[position++];
                high ^= _sBox8[temp & 0x3F] ^
                                _sBox6[(temp >> 8) & 0x3F] ^
                                _sBox4[(temp >> 16) & 0x3F] ^
                                _sBox2[(temp >> 24) & 0x3F];
                temp = ((low << 28) | (low >> 4)) ^ _expandedKey[position];
                high ^= _sBox7[temp & 0x3F] ^
                                _sBox5[(temp >> 8) & 0x3F] ^
                                _sBox3[(temp >> 16) & 0x3F] ^
                                _sBox1[(temp >> 24) & 0x3F];
                temp = high;
                high = low;
                low = temp;
                // Decryption uses the expanded key words in paired reverse
                // order.
                position -= 3;
            }

            // Reverse the initial permutation.
            IPInverse(ref low, ref high);

            // Set the return values.
            cipher[1] = high;
            cipher[0] = low;
        }

        /// <summary>
        /// Encrypts a single block of bytes, writing the result into the
        /// provided array.
        /// </summary>
        /// <param name="block">
        /// The block of bytes to be encrypted.
        /// </param>
        protected override void EncryptBlock(byte[] block)
        {
            uint[] words = Utils.BytesToWordsBigEndian(block);
            Encrypt(words);
            Utils.WriteWordsIntoBytesBigEndian(words, block);
        }

        /// <summary>
        /// Decrypts a single block of bytes, writing the result into the
        /// provided array.
        /// </summary>
        /// <param name="block">
        /// The block of bytes to be decrypted.
        /// </param>
        protected override void DecryptBlock(byte[] block)
        {
            uint[] words = Utils.BytesToWordsBigEndian(block);
            Decrypt(words);
            Utils.WriteWordsIntoBytesBigEndian(words, block);
        }

        /// <summary>
        /// Clears all potentially sensitive data stores.
        /// </summary>
        protected internal override void Reset()
        {
            if (_key != null)
            {
                Array.Clear(_key, 0, _key.Length);
            }
            if (_expandedKey != null)
            {
                Array.Clear(_expandedKey, 0, _expandedKey.Length);
            }
            base.Reset();
        }
    }
}
